//
//  HomePageController.m
//  敢唆嘛!
//
//  Created by lanou on 15/11/24.
//  Copyright © 2015年 zms. All rights reserved.
//

#import "HomePageController.h"
#import "Device.h"
#import "Define.h"
#import "MyCollectionCell.h"
#import "MyCollectModel.h"
#import "ChineseToPinyin.h"

@interface HomePageController () <UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong)UITableView *myCollectTableView;
@property(nonatomic, strong)NSMutableArray *collectArray;
@property(nonatomic, strong)BmobUser *bmobUser;
@property(nonatomic, strong)NSString *collectObjectId;  // 记录collectObjectId
@property(nonatomic, strong)UILabel *promptLabel;
@end

static NSString *cellIdentifier = @"collect";
@implementation HomePageController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationItem.title = @"我的主页";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 创建左上角返回按钮
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, KSWidth / 18, KSWidth / 18);
    [backBtn setImage:[UIImage imageNamed:@"iconfont-unie61e"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBackBtn = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftBackBtn;
    

    
    //创建背景图片
    self.placeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KSWidth, KSHeight/3)];
    
    self.placeImageView.image = [UIImage imageNamed:@"placeView.png"];
    
    self.placeImageView.alpha = 0.7;
    
    [self.view addSubview:_placeImageView];
    
    //用户头像
    float userHeight = KSWidth/5;
    //不能用imageView 他没有约束 添加的图片还是正方形的 将用户的头像放到button上
    self.userHeaderButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.userHeaderButton.frame = CGRectMake((KSWidth-userHeight)/2, KSHeight/15, userHeight, userHeight);
    
    [self.userHeaderButton.layer setCornerRadius:userHeight/2];
    
    [self.view addSubview:_userHeaderButton];
    
    //用户名字
    self.userLabel = [[UILabel alloc]initWithFrame:CGRectMake((KSWidth-KSWidth/3)/2, KSHeight/13+userHeight, KSWidth/3, 30) ];
    self.userLabel.textColor = [UIColor whiteColor];
    
    self.userLabel.textAlignment = NSTextAlignmentCenter;
    
    

    
    //用户的个性签名
    self.signatureLabel = [[UILabel alloc]initWithFrame:CGRectMake((KSWidth-KSWidth/3)/4,KSHeight/13+userHeight+30, KSWidth/1.5, 30) ];
    
    self.signatureLabel.textColor = [UIColor whiteColor];
    
    self.signatureLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.view addSubview:_signatureLabel];
    
    //赋值
    BmobUser *bUser = [BmobUser getCurrentUser];
    
    if (bUser) {
        BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
        
        [bquery getObjectInBackgroundWithId:bUser.objectId block:^(BmobObject *object, NSError *error) {
            if (object) {
                //找到图片所在的文件
                BmobFile *file = [object objectForKey:@"userHeader"];
                if (file != nil) {
                    
                    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
                    [imageView sd_setImageWithURL:[NSURL URLWithString:file.url]];
                    NSLog(@"%@",imageView.image);
                    [self.userHeaderButton setImage:imageView.image forState:UIControlStateNormal];
                }
                else{
                   [self.userHeaderButton setImage:[UIImage imageNamed:@"user"] forState:UIControlStateNormal];
                }
                
                //赋值用户名
                self.userLabel.text = bUser.username;
                
                //赋值个性签名
                if (![object objectForKey:@"signature"]) {
                    self.signatureLabel.text = @"故事让我们相遇";
                }
                else{
                self.signatureLabel.text = [object objectForKey:@"signature"];
                }
            }
            
        }];
        
    }
    
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, self.placeImageView.frame.size.height, KSWidth, 40)];
    myView.backgroundColor = [UIColor colorWithRed:245 / 255.0 green:245 / 255.0 blue:245 / 255.0 alpha:1.0];
    [self.view addSubview:myView];
    UILabel *myCollectLabel = [[UILabel alloc] initWithFrame:CGRectMake((myView.frame.size.width - myView.frame.size.width / 2) / 2, self.placeImageView.frame.size.height, myView.frame.size.width / 2, 40)];
    myCollectLabel.text = @"我的收藏";
    myCollectLabel.textAlignment = NSTextAlignmentCenter;
    myCollectLabel.font = [UIFont systemFontOfSize:KSWidth / 25];
    [self.view addSubview:myCollectLabel];
    
    self.myCollectTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.placeImageView.frame.size.height + myView.frame.size.height, KSWidth, KSHeight - self.placeImageView.frame.size.height - myView.frame.size.height) style:UITableViewStyleGrouped];
    self.myCollectTableView.backgroundColor = [UIColor whiteColor];
    self.myCollectTableView.delegate = self;
    self.myCollectTableView.dataSource = self;
    [self.myCollectTableView registerClass:[MyCollectionCell class] forCellReuseIdentifier:cellIdentifier];
    [self.view addSubview:_myCollectTableView];
    
    [self.view addSubview:_userLabel];
    
    self.promptLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, (KSHeight - ((KSWidth - 64) / 19)) / 1.5, KSWidth , (KSWidth - 64) / 19)];
    self.promptLabel.alpha = 0.6;
    self.promptLabel.text = @"暂无收藏哟~";
    self.promptLabel.textColor = [UIColor blackColor];
    self.promptLabel.font = [UIFont systemFontOfSize:KSWidth / 20];
    self.promptLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_promptLabel];
    
    [self findAllCollectData];
    
    
//    //创建segment的表头数组
//    NSArray *titleArray = @[@"我的故事", @"我的收藏", @"我的推荐"];
//    
//    UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:titleArray];
//    
//    segment.frame = CGRectMake(20, self.placeImageView.frame.size.height+15, KSWidth-40, 40);
//    
//    //填充颜色是否立即消失
//    segment.momentary = NO;
//    
//    segment.tintColor = [UIColor blackColor];
//    
//    //一上来 那个下标处的标题就是被选中的状态
//    segment.selectedSegmentIndex = 0;
//    
//    //segment添加触发方法
//    [segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
//    
//    [self.view addSubview:segment];
}

// 查询bmob数据库表内所有内容 最多1000 默认100
- (void)findAllCollectData
{
    // 获取当前登录的用户
    self.bmobUser = [BmobUser getCurrentUser];
    // 把名字转化为拼音
    NSString *string = [ChineseToPinyin pinyinFromChiniseString:_bmobUser.username];
    
    BmobQuery *bquery = [BmobQuery queryWithClassName:[NSString stringWithFormat:@"%@Collection",string]];
    [bquery orderByDescending:@"createdAt"];
    bquery.limit = 1000;
    //查找Recommend表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error)
        {
            // 判断网络连接
            if (![[NetWorkState shareInstance] reachability])
            {
                [self alertActionWithTitle:@"提示" message:@"网络不通" other:@"确定"];
            };
            NSLog(@"error:%@",error);
        }
        else
        {
            // 数据请求成功后才初始化数组 否则会造成下拉刷新崩溃
            self.collectArray = [NSMutableArray array];
            for (BmobObject *obj in array)
            {
                MyCollectModel *model = [[MyCollectModel alloc] initWithObj:obj];
                [self.collectArray addObject:model];
            }
            // 需要在主线程里面进行刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.myCollectTableView reloadData];
            });
        }
    }];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.collectArray.count != 0)
    {
        [cell setModel:self.collectArray[indexPath.row]];
        self.promptLabel.hidden = YES;
    }
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_collectArray.count == 0)
    {
        return 0;
    }
    else
    {
         return self.collectArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_collectArray.count == 0)
    {
        return 0;
    }
    else
    {
        return 50;
    }
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.myCollectTableView setEditing:editing animated:animated];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        // 删除数据库内数据
        MyCollectModel *model = self.collectArray[indexPath.row];
        [self findUserCollectionTableObjectId:model];
        [self.collectArray removeObjectAtIndex:indexPath.row];
        
            // 更新界面
        [self.myCollectTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        
        if (self.collectArray.count == 0)
        {
            self.promptLabel.hidden = NO;
        }
        

    }
}

// #warning 查询用户收藏表查询数据 获得objectId
- (void)findUserCollectionTableObjectId:(MyCollectModel *)model
{
    // 获取当前登录的用户
    self.bmobUser = [BmobUser getCurrentUser];
    // 把名字转化为拼音
    NSString *string = [ChineseToPinyin pinyinFromChiniseString:_bmobUser.username];
    BmobQuery *bquery = [BmobQuery queryWithClassName:[NSString stringWithFormat:@"%@Collection",string]];
    //查找当前用户的收藏表的数据
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        for (int i = 0; i < array.count; i++)
        {
            BmobObject *obj = array[i];
            
            if ([model.realityObjectId isEqualToString: [obj objectForKey:@"realityObjectId"]])
            {
                // 存在数据 获取objectId
                self.collectObjectId = [obj objectId];
                // 删除
                [self deleteUserCollectionTable];
            }
        }
    }];
}

// #warning 根据用户名删除一个收藏表的数据
- (void)deleteUserCollectionTable
{
    // 获取当前登录的用户
    self.bmobUser = [BmobUser getCurrentUser];
    // 把名字转化为拼音
    NSString *string = [ChineseToPinyin pinyinFromChiniseString:_bmobUser.username];
    BmobObject *bmobObject = [BmobObject objectWithoutDatatWithClassName:[NSString stringWithFormat:@"%@Collection",string]  objectId:_collectObjectId];
    
    [bmobObject deleteInBackgroundWithBlock:^(BOOL isSuccessful, NSError *error) {
        if (isSuccessful) {
            //删除成功后的动作
            NSLog(@"successful");
            // 替换收藏图片
//            self.collectionImageView.image = [UIImage imageNamed:@"iconfont-xingxing-1"];
//            [self promptViewWithTitle:@"取消收藏" buttonEnabled:self.collectionBtn];
            self.collectObjectId = nil;
//            collectState = collectOff;
            // #warning 更新收藏数
//            [self updateRealityTableCollection];
            
        } else if (error){
            NSLog(@"%@",error);
        } else {
            NSLog(@"UnKnow error");
        }
    }];
}


// 返回按钮触发
- (void)backBtnAction:(UIButton *)backBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}


//#pragma mark-- segment的触发事件--
//-(void)segmentAction:(UISegmentedControl *)segment{
//    
//    //无论点击那一个 都让所有controller的视图隐藏
//    for (UIViewController *vc in self.childViewControllers) {
//        
//        vc.view.hidden =YES;
//    }
//    
//    //通过segment的下标 来取数组中与之对应的controller
//    //让该controller的view 显现出来
//    UIViewController *vc = self.childViewControllers[segment.selectedSegmentIndex ];
//    
//    vc.view.hidden = NO;
// 
//    
//}

// 弹出视图
- (void)alertActionWithTitle:(NSString *)title message:(NSString *)message other:(NSString *)other
{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:other style:UIAlertActionStyleDefault handler:nil];
    [alertVc addAction:otherAction];
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
